package com.app.aipass.fragment.my.paytype.addpaytype;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.app.AppViewModelFactory;
import com.app.aipass.app.Constants;
import com.app.aipass.databinding.FragmentAddWxBinding;
import com.app.aipass.entity.Message;
import com.app.aipass.entity.PayAccountEntity;
import com.app.aipass.entity.UploadFileEntity;
import com.app.aipass.utils.GlideUtils;
import com.app.aipass.utils.StatusBarUtil;
import com.app.aipass.utils.TextUtil;
import com.app.aipass.utils.ToastUtil;
import com.app.aipass.view.CustomPopWindow;
import com.lwkandroid.imagepicker.ImagePicker;
import com.lwkandroid.imagepicker.data.ImageBean;
import com.lwkandroid.imagepicker.data.ImageContants;
import com.lwkandroid.imagepicker.data.ImagePickType;
import com.lwkandroid.imagepicker.ui.grid.view.ImageDataActivity;
import com.lwkandroid.imagepicker.utils.GlideImagePickerDisplayer;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;

/**
 * @author: woking
 * @date: 2021/6/11
 * @description：
 */
public class AddWXFragment extends BaseFragment<FragmentAddWxBinding, AddPayTypeViewModel> {
    private Disposable mSubscription;
    private String imagePath = "";
    private String imageUrl = "";
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_add_wx;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
    @Override
    public AddPayTypeViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(AddPayTypeViewModel.class);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscription != null)
        {
            RxSubscriptions.remove(mSubscription);
        }
    }
    private long idPayAccount = -1;
    private void setEnable(boolean isEnAble)
    {
        binding.userNameEt.setEnabled(isEnAble);
        binding.wxNoEt.setEnabled(isEnAble);
        if(isEnAble)
        {
            binding.codeRl.setVisibility(View.VISIBLE);
            binding.saveTv.setVisibility(View.VISIBLE);
        }
        else
        {
            binding.codeRl.setVisibility(View.GONE);
            binding.saveTv.setVisibility(View.GONE);
        }
    }
    @Override
    public void initData() {
        super.initData();
//        binding.wxNoEt.setText("wx3333333");
//        binding.userNameEt.setText("wxshoukuanren");
//        binding.codeEt.setText("88888888");
        if (getArguments() != null) {
            PayAccountEntity entity = (PayAccountEntity)getArguments().getSerializable("entity");
            binding.userNameEt.setText(entity.name);
            binding.wxNoEt.setText(entity.account);
            imagePath = entity.image;
            binding.tvTitleText.setText("微信");
            GlideUtils.getInstances().loadNormalImg(getActivity(),binding.addImg,entity.image);
            idPayAccount = entity.id;
            setEnable(false);
        }
        if(idPayAccount != -1)
        {
            binding.tvRightText.setVisibility(View.VISIBLE);
            binding.tvRightText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(binding.saveTv.getVisibility() == View.VISIBLE)
                    {
                        binding.tvRightText.setText("编辑");
                        setEnable(false);
                    }
                    else
                    {
                        binding.tvRightText.setText("取消");
                        setEnable(true);
                    }
                }
            });
        }
        else
        {
            binding.tvRightText.setVisibility(View.GONE);
        }
        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
                        Log.e("TAG","===============message=============="+message.getName());
                        if(message.getName().equals("update_pay_type"))
                        {
                            getActivity().finish();
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);

        binding.ivTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        binding.addImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                selectPictur();
                if(binding.saveTv.getVisibility() == View.VISIBLE)
                {
                    selectPictur();
                }
                else
                {
                    popFuKuan(binding.addImg,imagePath);
                }
            }
        });
        binding.getcodeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.smsCode((TextView)view);
            }
        });
        binding.saveTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payAccountCreate();
            }
        });
//        viewModel.qiniuToken();

        viewModel.mUploadFileEntity.observe(this, new Observer<UploadFileEntity>() {
            @Override
            public void onChanged(UploadFileEntity uploadFileEntity) {
                if(uploadFileEntity != null)
                {
                    GlideUtils.getInstances().loadNormalImg(getActivity(),binding.addImg,uploadFileEntity.url);
                }
            }
        });
    }

    private boolean parseInfo()
    {
        String account = binding.wxNoEt.getText().toString();
        if(TextUtil.isEmpty(account))
        {
            ToastUtil.showToast("请输入微信账号");
            return false;
        }
        String name = binding.userNameEt.getText().toString();
        if(TextUtil.isEmpty(name))
        {
            ToastUtil.showToast("请输入收款人姓名");
            return false;
        }
        String code = binding.codeEt.getText().toString();
        if(TextUtil.isEmpty(code))
        {
            ToastUtil.showToast("请输入验证码");
            return false;
        }
        if(viewModel.mUploadFileEntity.getValue() == null || TextUtil.isEmpty(viewModel.mUploadFileEntity.getValue().url))
        {
            if(TextUtil.isEmpty(imagePath))
            {
                ToastUtil.showToast("请添加收款二维码");
                return false;
            }
        }
        return true;
    }
    private void payAccountCreate()
    {
        if(!parseInfo())
        {
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        //银行卡 {"type": 1,"account": "Entity","name": "Unpro","address": "dsfdsfds","branch": "branch","code": 1234}
        map.put("type", 3);
//        map.put("account", "622161616166161");
//        map.put("name", "吕迅");
//        map.put("address", "eeeeeeee");
//        map.put("branch", "平安支行");
//        map.put("code", "88888888");
        map.put("account", binding.wxNoEt.getText().toString());
        map.put("name", binding.userNameEt.getText().toString());
//        map.put("address", "");
//        map.put("branch", "");
//        map.put("image",viewModel.mUploadFileEntity.getValue().path);

        if(idPayAccount != -1)
        {
            map.put("id", idPayAccount+"");
        }

        if(viewModel.mUploadFileEntity.getValue() == null || TextUtil.isEmpty(viewModel.mUploadFileEntity.getValue().url))
        {
            if(!TextUtil.isEmpty(imagePath))
            {
                map.put("image",imagePath);
            }
        }
        else
        {
            map.put("image",viewModel.mUploadFileEntity.getValue().path);
        }
        map.put("code", binding.codeEt.getText().toString());

        viewModel.payAccountCreate(3,map);
    }


    private int code;
    public void selectPictur()
    {
        code = Constants.INTENT_REQUESTCODE_VERIFIED_IMG1;
//        closeKeyBoard();
        new RxPermissions(this).requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted && Manifest.permission.CAMERA.equals(permission.name)) {
                            // 用户已经同意该权限
                            ImagePicker imagePicker = new ImagePicker()
                                    .pickType(ImagePickType.SINGLE)//设置选取类型(拍照、单选、多选)
                                    .maxNum(1)//设置最大选择数量(拍照和单选都是1，修改后也无效)
                                    .needCamera(true)//是否需要在界面中显示相机入口(类似微信)
                                    .displayer(new GlideImagePickerDisplayer())//自定义图片加载器，默认是Glide实现的,可自定义图片加载器
                                    // .doCrop(1, 1, 300, 300)
                            ;
                            //.start(AddWXFragment.this, code);

                            Intent intent = new Intent(getActivity(), ImageDataActivity.class);
                            intent.putExtra(ImageContants.INTENT_KEY_OPTIONS, imagePicker.getOptions());
                            startActivityForResult(intent, code);
                        }
                    }
                });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("TAG","==========imageUrl========1111======");
        if (resultCode == Activity.RESULT_OK && data != null) {
            List<ImageBean> resultList = data.getExtras().getParcelableArrayList(ImagePicker.INTENT_RESULT_DATA);

            if (resultList != null && resultList.size() > 0) {
                imageUrl = resultList.get(0).getImagePath();
                Log.e("TAG","==========imageUrl=============="+imageUrl);

//                GlideUtils.getInstances().loadNormalImg(getActivity(),binding.addImg,imageUrl);
                viewModel.uploadFiles(imageUrl);
            }
            if (requestCode == Constants.INTENT_REQUESTCODE_VERIFIED_IMG1) {
//                uploadImg(imageUrl, 1);
            }

        }
    }

    private CustomPopWindow mCustomPopWindow;
    private void popFuKuan(View view,String url)
    {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_fukuan_img,null);
        contentView.findViewById(R.id.fukuan_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCustomPopWindow.dissmiss();
            }
        });
        GlideUtils.getInstances().loadNormalImg(getContext(),contentView.findViewById(R.id.fukuan_img),url);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.3f) // 控制亮度
                .setFocusable(true)
                .setOutsideTouchable(true)
//                .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .size(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .create()
                .showAtLocation(view, Gravity.CENTER,0,20);
//                .showAsDropDown(view,0,20);
    }
}
